import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  getPatientAppointments,
  getCurrentClinicStaff,
  getQueue,
  updatePatientAppStatus,
  callSlot,
  convertToChineseTime,
  formatAppointmentStatus,
  formatBookedAt,
  type AppointmentQueryParams,
  type AppointmentInfo,
  type DoctorClinicInfo,
  type QueueItem,
  type UpdateAppointmentStatusRequest
} from '@/api/appointment/appapi'
import { useUserStore } from '@/stores/modules/user'
export interface Appointment {
  id: string
  patientId: string
  patientName: string
  appointmentDate: string
  appointmentTime: string
  type: '初诊' | '复诊' | '急诊' | '体检'
  status: '已预约' | '已确认' | '已完成' | '已取消' | '未到诊'
  reason: string
  priority: '普通' | '紧急' | '加急'
  fee: number
  paymentStatus: '未支付' | '已支付' | '已退款'
  notes: string
  createdAt: string
  updatedAt: string
  queueNumber: number
  estimatedTime: string
  reminderSent: boolean
  // 新增字段，对应API响应
  period?: '上午' | '下午'
  slotNo?: number
  bookedAt?: string
  cancelReason?: string
}

export const useAppointmentStore = defineStore('appointment', () => {
  const appointments = ref<Appointment[]>([
    {
      id: 'A001',
      patientId: 'P001',
      patientName: '张三',
      appointmentDate: '2024-01-25',
      appointmentTime: '09:00',
      type: '复诊',
      status: '已预约',
      reason: '糖尿病复查',
      priority: '普通',
      fee: 50,
      paymentStatus: '已支付',
      notes: '需要空腹检查',
      createdAt: '2024-01-20T10:30:00',
      updatedAt: '2024-01-20T10:30:00',
      queueNumber: 5,
      estimatedTime: '09:30',
      reminderSent: false
    }
  ])
  const userStore = useUserStore()
  const userInfo = userStore.userInfo
  const staffId = userInfo?.staff?.staffId
  const deptId = userInfo?.staff?.deptId
  const currentAppointment = ref<Appointment | null>(null)
  const searchQuery = ref('')
  const filterStatus = ref('')
  const filterDate = ref('')
  const filterDoctor = ref('')
  const loading = ref(false)

  // 新增状态管理
  const apiAppointments = ref<AppointmentInfo[]>([]) // 存储从API获取的原始数据
  const totalCount = ref(0) // 总数量
  const currentPage = ref(1) // 当前页码
  const pageSize = ref(5) // 每页大小
  
  // 新增：医生坐诊信息状态
  const doctorClinicInfo = ref<DoctorClinicInfo[]>([])
  const clinicLoading = ref(false)

  // 新增：叫号队列状态
  const queueList = ref<QueueItem[]>([])
  const queueLoading = ref(false)

  // 获取预约列表 (原有方法，保持兼容性)
  const getAppointments = async (params?: any) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      return appointments.value
    } finally {
      loading.value = false
    }
  }

  // 新增：从API获取患者预约列表
  const getPatientAppointmentsFromAPI = async (params: Partial<AppointmentQueryParams>) => {
    loading.value = true
    try {
      const queryParams: AppointmentQueryParams = {
        staffId: staffId, // 默认员工ID
        typeId: 1, // 默认类型ID
        bookedAt: params.bookedAt || formatBookedAt(new Date().toISOString().split('T')[0], '上午'),
        period: params.period ,
        pageNum: params.pageNum || currentPage.value,
        pageSize: params.pageSize || pageSize.value,
        ...params
      }
      const response = await getPatientAppointments(queryParams)
      console.log("11  ss",staffId)
      // 更新状态（增加兜底，防止空数据）
      const list = response.data?.content ?? []
      apiAppointments.value = list.map(item => ({
        ...item,
        // 转换UTC时间为中国时间
        bookedAt: convertToChineseTime(item.bookedAt)
      }))

      // 正确设置总记录数 - 从API响应中获取totalElements
      totalCount.value = Number(response.data?.totalElements) || 0
      currentPage.value = (response.data?.pageable?.pageNumber ?? 0) + 1 // API返回的是0基础的页码

      // 同时更新本地appointments数组以保持兼容性
      const convertedAppointments: Appointment[] = list.map(item => ({
        id: item.id,
        patientId: item.patientId,
        patientName: item.patientName,
        // 统一本地存储的日期格式，避免被 filterDate 二次筛选时全被过滤
        appointmentDate: convertToChineseTime(item.bookedAt).split(' ')[0].replace(/\//g, '-'),
        appointmentTime: item.period === '上午' ? '09:00' : '14:00',
        type: '初诊',
        status: formatAppointmentStatus(item.status) as Appointment['status'],
        reason: '',
        priority: '普通',
        fee: 0,
        paymentStatus: '未支付',
        notes: item.cancelReason || '',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        queueNumber: item.slotNo,
        estimatedTime: '',
        reminderSent: false,
        period: item.period,
        slotNo: item.slotNo,
        bookedAt: convertToChineseTime(item.bookedAt),
        cancelReason: item.cancelReason
      }))

      // 更新本地数据
      appointments.value = convertedAppointments

      return {
        content: apiAppointments.value,
        pageable: response.data?.pageable,
        total: totalCount.value,
        totalElements: totalCount.value,
        totalPages: response.data?.totalPages || Math.ceil(totalCount.value / pageSize.value)
      }
    } catch (error) {
      console.error('获取预约列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 新增：获取当天医生坐诊信息
  const getDoctorClinicInfo = async (staffId: string) => {
    clinicLoading.value = true
    try {
      const response = await getCurrentClinicStaff(staffId)
      doctorClinicInfo.value = response.data || []
      return doctorClinicInfo.value
    } catch (error) {
      console.error('获取医生坐诊信息失败:', error)
      doctorClinicInfo.value = []
      throw error
    } finally {
      clinicLoading.value = false
    }
  }

  // 新增：获取叫号队列
  const getQueueData = async (staffId: string, clinicId: string) => {
    queueLoading.value = true
    try {
      const response = await getQueue(staffId, clinicId)
      queueList.value = response.data || []
      return queueList.value
    } catch (error) {
      console.error('获取叫号队列失败:', error)
      queueList.value = []
      throw error
    } finally {
      queueLoading.value = false
    }
  }

  // 根据ID获取预约
  const getAppointmentById = (id: string) => {
    return appointments.value.find(a => a.id === id)
  }

  // 根据患者ID获取预约
  const getAppointmentsByPatient = (patientId: string) => {
    return appointments.value.filter(a => a.patientId === patientId)
  }

  // 根据医生ID获取预约
  const getAppointmentsByDoctor = (doctorId: string) => {
    return appointments.value.filter(a => a.doctorId === doctorId)
  }

  // 根据日期获取预约
  const getAppointmentsByDate = (date: string) => {
    return appointments.value.filter(a => a.appointmentDate === date)
  }

  // 创建预约
  const createAppointment = async (appointment: Omit<Appointment, 'id' | 'createdAt' | 'updatedAt' | 'queueNumber' | 'estimatedTime' | 'reminderSent'>) => {
    loading.value = true
    try {
      // 检查时间冲突
      const conflictAppointment = appointments.value.find(a => 
        a.doctorId === appointment.doctorId &&
        a.appointmentDate === appointment.appointmentDate &&
        a.appointmentTime === appointment.appointmentTime &&
        a.status !== '已取消'
      )
      
      if (conflictAppointment) {
        throw new Error('该时间段已被预约')
      }

      // 生成排队号
      const dateAppointments = getAppointmentsByDate(appointment.appointmentDate)
        .filter(a => a.doctorId === appointment.doctorId && a.status !== '已取消')
      const queueNumber = dateAppointments.length + 1

      // 估算就诊时间（每位患者15分钟）
      const baseTime = new Date(`${appointment.appointmentDate} ${appointment.appointmentTime}`)
      const estimatedTime = new Date(baseTime.getTime() + (queueNumber - 1) * 15 * 60000)
      
      const newAppointment: Appointment = {
        ...appointment,
        id: `A${Date.now()}`,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        queueNumber,
        estimatedTime: estimatedTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
        reminderSent: false
      }
      
      appointments.value.unshift(newAppointment)
      return newAppointment
    } finally {
      loading.value = false
    }
  }

  // 更新预约
  const updateAppointment = async (id: string, updates: Partial<Appointment>) => {
    loading.value = true
    try {
      const index = appointments.value.findIndex(a => a.id === id)
      if (index > -1) {
        appointments.value[index] = { 
          ...appointments.value[index], 
          ...updates,
          updatedAt: new Date().toISOString()
        }
        return appointments.value[index]
      }
      throw new Error('预约不存在')
    } finally {
      loading.value = false
    }
  }

  // 取消预约
  const cancelAppointment = async (id: string, reason: string) => {
    return updateAppointment(id, { 
      status: '已取消', 
      notes: `${appointments.value.find(a => a.id === id)?.notes || ''}\n取消原因: ${reason}` 
    })
  }

  // 确认预约
  const confirmAppointment = async (id: string) => {
    return updateAppointment(id, { status: '已确认' })
  }

  // 完成预约
  const completeAppointment = async (id: string) => {
    return updateAppointment(id, { status: '已完成' })
  }

  // 标记未到诊
  const markNoShow = async (id: string) => {
    return updateAppointment(id, { status: '未到诊' })
  }

  // 搜索预约
  const searchAppointments = (query: string) => {
    searchQuery.value = query
    if (!query) return appointments.value
    
    return appointments.value.filter(appointment => 
      appointment.patientName.includes(query) ||
      appointment.doctorName.includes(query) ||
      appointment.department.includes(query) ||
      appointment.reason.includes(query)
    )
  }

  // 按状态筛选
  const filterAppointmentsByStatus = (status: string) => {
    filterStatus.value = status
    if (!status) return appointments.value
    
    return appointments.value.filter(appointment => appointment.status === status)
  }

  // 按日期筛选
  const filterAppointmentsByDate = (date: string) => {
    filterDate.value = date
    if (!date) return appointments.value
    
    return appointments.value.filter(appointment => appointment.appointmentDate === date)
  }

  // 按医生筛选
  const filterAppointmentsByDoctor = (doctorId: string) => {
    filterDoctor.value = doctorId
    if (!doctorId) return appointments.value
    
    return appointments.value.filter(appointment => appointment.doctorId === doctorId)
  }

  // 检查时间可用性
  const checkTimeAvailability = (doctorId: string, date: string, time: string) => {
    const existingAppointment = appointments.value.find(a => 
      a.doctorId === doctorId &&
      a.appointmentDate === date &&
      a.appointmentTime === time &&
      a.status !== '已取消'
    )
    
    return !existingAppointment
  }

  // 获取医生的预约时间段
  const getDoctorAvailableSlots = (doctorId: string, date: string) => {
    const timeSlots = [
      '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30',
      '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30'
    ]
    
    const bookedSlots = appointments.value
      .filter(a => 
        a.doctorId === doctorId && 
        a.appointmentDate === date && 
        a.status !== '已取消'
      )
      .map(a => a.appointmentTime)
    
    return timeSlots.filter(slot => !bookedSlots.includes(slot))
  }

  // 发送提醒
  const sendReminder = async (id: string) => {
    loading.value = true
    try {
      const appointment = appointments.value.find(a => a.id === id)
      if (appointment) {
        // 模拟发送提醒
        await new Promise(resolve => setTimeout(resolve, 1000))
        appointment.reminderSent = true
        return true
      }
      return false
    } finally {
      loading.value = false
    }
  }

  // 获取统计数据
  const getAppointmentStats = () => {
    const total = appointments.value.length
    const byStatus = appointments.value.reduce((acc, appointment) => {
      acc[appointment.status] = (acc[appointment.status] || 0) + 1
      return acc
    }, {} as Record<string, number>)
    
    const byType = appointments.value.reduce((acc, appointment) => {
      acc[appointment.type] = (acc[appointment.type] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const byDepartment = appointments.value.reduce((acc, appointment) => {
      acc[appointment.department] = (acc[appointment.department] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const totalRevenue = appointments.value
      .filter(a => a.paymentStatus === '已支付')
      .reduce((sum, a) => sum + a.fee, 0)

    const todayAppointments = appointments.value.filter(a => 
      a.appointmentDate === new Date().toISOString().split('T')[0]
    ).length

    return {
      total,
      byStatus,
      byType,
      byDepartment,
      totalRevenue,
      todayAppointments
    }
  }
  
  // 新增：更新预约状态
  const updateAppointmentStatus = async (params: UpdateAppointmentStatusRequest) => {
    try {
      const response = await updatePatientAppStatus(params)
      return response
    } catch (error) {
      console.error('更新预约状态失败:', error)
      throw error
    }
  }

  // 新增：叫号
  const callSlotApi = async (id: string) => {
    try {
      const response = await callSlot(id)
      return response
    } catch (error) {
      console.error('叫号失败:', error)
      throw error
    }
  }

  return {
    appointments,
    currentAppointment,
    searchQuery,
    filterStatus,
    filterDate,
    filterDoctor,
    loading,
    // 新增状态
    apiAppointments,
    totalCount,
    currentPage,
    pageSize,
    doctorClinicInfo,
    clinicLoading,
    queueList,
    queueLoading,
    // 原有方法
    getAppointments,
    getAppointmentById,
    getAppointmentsByPatient,
    getAppointmentsByDoctor,
    getAppointmentsByDate,
    createAppointment,
    updateAppointment,
    cancelAppointment,
    confirmAppointment,
    completeAppointment,
    markNoShow,
    searchAppointments,
    filterAppointmentsByStatus,
    filterAppointmentsByDate,
    filterAppointmentsByDoctor,
    checkTimeAvailability,
    getDoctorAvailableSlots,
    sendReminder,
    getAppointmentStats,
    // 新增方法
    getPatientAppointmentsFromAPI,
    getDoctorClinicInfo,
    getQueueData,
    updateAppointmentStatus,
    callSlotApi
  }
}, {
  persist: {
    key: 'appointment-store',
    storage: localStorage
  }
})